package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.warrior.entity.ActivityEntity;
import com.warrior.entity.HomeIntroductionEntity;
import com.warrior.entity.IntroductionContentEntity;
import com.warrior.entity.UserEntity;
import com.warrior.service.ActivityService;
import com.warrior.service.HomeIntroductionService;
import com.warrior.service.UserService;
import com.warrior.util.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 首页controller
 * Created by Shawn on 2017/3/24.
 */
@Controller
@RequestMapping("/home")
public class HomeIntroductionController {

    private static final Logger logger = LogManager.getLogger(HomeIntroductionController.class.getName());

    @Autowired
    private HomeIntroductionService homeIntroductionService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserService userService;


    /**
     * 首页访问获取授权
     * @return String
     */
    @RequestMapping("/getLoginToken")
    public String loginToken(){
        WxChatAuthTools wxChatAuthTools = new WxChatAuthTools();
        String wxCode = wxChatAuthTools.getWxCode(0, "");
        logger.debug("wxcode="+wxCode);
        return "redirect:"+wxCode;
    }

    /**
     * 首页跳转路由
     *
     * @return ModelAndView
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(String page, HttpServletRequest request, HttpServletResponse response, String code) throws IOException {
        logger.debug("/index");
        //微信登陆授权code
        logger.debug("code" + code);
        this.userLogin(request,code);
        if (null == page) {
            page = "0";
        }
        ModelAndView mv = new CModelAndView("/index", request, response);
        //查出首推活动
        ActivityEntity recommendActivity = this.activityService.getRecommendActivity();
        mv.addObject("recommendActivity", recommendActivity);
        //查出首页介绍
        Page<HomeIntroductionEntity> homeIntroductionEntities = this.homeIntroductionService.listAllHomeIntroduction(3, Integer.parseInt(page));
        mv.addObject("homeIntroductionEntities", homeIntroductionEntities);
        if (logger.isDebugEnabled()) {
            logger.debug("index(String, HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return mv;
    }

    public void userLogin(HttpServletRequest request,String code) throws IOException {
        //如果没有微信登陆,则跳过微信写入
        if ((null != code) && !"".equals(code)) {
            //拿到code之后换取用户token
            WxChatAuthTools wxChatAuthTools = new WxChatAuthTools();
            String loginToken = wxChatAuthTools.getLoginToken(code);
            ObjectMapper mapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            Map returnData = mapper.readValue(loginToken, Map.class);
            String access_token = (String) returnData.get("access_token");
            logger.debug("access_token:"+access_token);
            String openId = (String) returnData.get("openid");
            logger.debug("openId"+openId);
            //根据这个access_token查询用户信息
            if (null!=access_token && !"".equals(access_token) && null!= openId && !"".equals(openId)  ){
                //如果用户为空则在数据库中建立一个用户并且将用户id写进session,不为空则直接写入
                UserEntity userEntity = this.userService.findUserByToken(openId);
                if (null!=userEntity){
                    //找到了该用户,将用户id写进session
                    logger.debug("find user");
                    request.getSession().setAttribute("userId",userEntity.getId());
                }else{
                    //用户第一次使用,写进数据库
                    UserEntity user = new UserEntity();
                    //获取用户信息
                    String userInfo = wxChatAuthTools.getUserInfo(access_token, openId);
                    Map  returnUserInfo = mapper.readValue(userInfo, Map.class);
                    user.setId("U-"+ UUID.randomUUID().toString().replace("-",""));
                    request.getSession().setAttribute("userId",user.getId());
                    DateUtil dateUtil = new DateUtil();
                    user.setWxChatToken(openId);
                    user.setCreatedBy("admin");
                    user.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
                    user.setIsCaption(0);
                    logger.debug("++++++++"+EmojiFilter.filterEmoji(returnUserInfo.get("nickname").toString()));
                    logger.debug("-----------"+CommonUtils.removeNonBmpUnicode(returnUserInfo.get("nickname").toString()));
                    user.setUserWxNickname(EmojiFilter.filterEmoji(returnUserInfo.get("nickname").toString()));
                    logger.debug("userName" +returnUserInfo.get("nickname"));
                    user.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
                    user.setUserStatus(1);
                    user.setUpdateBy("admin");
                    user.setUserWxPicPath((String) returnUserInfo.get("headimgurl"));
                    this.userService.saveUser(user);
                }
            }

        }
    }

    /**
     * 获取推荐的活动
     *
     * @param request  request
     * @param response response
     * @return json
     */
    @RequestMapping(value = "/getRecommendActivity")
    @ResponseBody
    public String getRecommendActivity(HttpServletRequest request, HttpServletResponse response) {
        if (logger.isDebugEnabled()) {
            logger.debug("getRecommendActivity(HttpServletRequest request={}, HttpServletResponse response={}) - start", request, response); //$NON-NLS-1$
        }

        ActivityEntity recommendActivity = this.activityService.getRecommendActivity();
        String returnMsg = "";
        try {
            returnMsg = ServerResponse.okToJsonString(recommendActivity);
            logger.debug("returnMsg" + returnMsg);

        } catch (JsonProcessingException e) {
            logger.error("getRecommendActivity(HttpServletRequest, HttpServletResponse)", e); //$NON-NLS-1$
            e.printStackTrace();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("getRecommendActivity(HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return returnMsg;
    }


    /**
     * 首页介绍的详细内容
     *
     * @param id       介绍的id
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/homeIntroduction", method = RequestMethod.GET)
    public ModelAndView homeIntroductionDetails(String id, HttpServletRequest request, HttpServletResponse response) {
        if (logger.isDebugEnabled()) {
            logger.debug("homeIntroductionDetails(String id={}, HttpServletRequest request={}, HttpServletResponse response={}) - start", id, request, response); //$NON-NLS-1$
        }

        ModelAndView mv = new CModelAndView("/warrior/activity/home_introduce", request, response);
        List<IntroductionContentEntity> contentEntities = this.homeIntroductionService.findContentByHomeId(id);
        HomeIntroductionEntity homeIntroductionEntity = this.homeIntroductionService.findHomeIntroductionById(id);
        mv.addObject("homeEntity",homeIntroductionEntity);
        mv.addObject("homeIntroduction", contentEntities);
        if (logger.isDebugEnabled()) {
            logger.debug("homeIntroductionDetails(String, HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return mv;
    }


    /**
     * 分页ajax请求数据
     * @param page 当前页 0开始
     * @param size 分页大小
     * @return
     */
    @RequestMapping(value = "/homeIntroductionByPage",method = RequestMethod.POST)
    @ResponseBody
    public String homeIntroductionByPage(String page,String size){
        Page<HomeIntroductionEntity> homeIntroductionEntities = this.homeIntroductionService.listAllHomeIntroduction(CommonUtils.String2Int(size), CommonUtils.String2Int(page));
        String returnMsg = "";
        try {
            returnMsg = ServerResponse.okToJsonString(homeIntroductionEntities);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return returnMsg;
    }


}
